import paho.mqtt.client as mqtt
import os
import time
import datetime
import base64
import hashlib
import json
import requests
#获取gpio2的数据
cmd = 'gpio read 2'
#需要换成自己的天翼云应用appkey和appsecret
app_key = '换成自己的appkey'
app_secret = '换成自己的appsecret'
request_url = "https://ai.ctyun.cn/v1/aiop/api/2gm0y369n30g/action/falldown/images"
def md5(key):
    input_name = hashlib.md5()
    input_name.update(key.encode("utf-8"))
    return input_name.hexdigest()

def is_fall(img_list):
    list=[]
    for img in img_list:
        f = open(img, 'rb')
        img_base64 = base64.b64encode(f.read()).decode()
        list.append(img_base64)
    time_stamp = str(int(round(time.time() * 1000)))
    payload = {'images': img_data}
    headers = {
        'content-type': 'application/json',
        'Sign': md5(
            app_key + app_secret + time_stamp + '/v1/aiop/api/2gm0y369n30g/action/falldown/images' + json.dumps(
                payload)),
        'Timestamp': time_stamp,
        'AppKey': app_key
    }
    response = requests.post(request_url, json.dumps(payload), headers=headers)
    response = json.loads(response.text)
    if(response['code'] == 0):
        if (response['result']['score'] > 35):
            client.publish('danger/fall', payload=list[5], qos=1)
            client.loop_start()
    else:
        client.publish('erro/device', payload="service erro", qos=1)
        client.loop_start()

def on_connect(client, userdata, flags, rc):
    print('Connected with result code '+str(rc))
    client.subscribe('get/#')


# 消息接收回调
def on_message(client, userdata, msg):
    numbers = 10
    img_list = []
    while (numbers != 0):
        time = datetime.datetime.now()
        curr_time = datetime.datetime.strftime(curr_time, '%Y-%m-%d-%H:%M:%S')
        take_pic = 'fswebcam -d /dev/video0 --no-banner -r 1280x720 /opt/images/' + curr_time + ".jpg"
        url = '/opt/images/' + curr_time + ".jpg"
        os.system(take_pic)
        img_list.append(url)
        numbers - -
    is_fall(img_list)


client = mqtt.Client("smartv1")
client.username_pw_set("123", password="123")

# 指定回调函数
client.on_connect = on_connect
client.on_message = on_message

# 建立连接
client.connect('101.43.251.24', 1883, 60)
while True:
    status = os.popen(cmd).read()
    #当传感器检测到有人时
    if(status==1):
        numbers = 10
        img_list=[]
        while(numbers!=0):
            time = datetime.datetime.now()
            curr_time = datetime.datetime.strftime(curr_time, '%Y-%m-%d-%H:%M:%S')
            take_pic = 'fswebcam -d /dev/video0 --no-banner -r 1280x720 /opt/images/' + curr_time + ".jpg"
            url = '/opt/images/' + curr_time + ".jpg"
            os.system(take_pic)
            img_list.append(url)
            numbers--
        is_fall(img_list)
        time.sleep(1)


